<?php

namespace App\V3\V3_2_7\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\LogInStorageModel;
use App\V3\V3_2_7\Models\LogOutStorageModel;
use App\V3\V3_2_7\Models\LogPackageModel;
use App\V3\V3_2_7\Models\MaterielModel;
use App\V3\V3_2_7\Models\OverflowBreakageModel;
use App\V3\V3_2_7\Models\ProductOrderModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\SupplierCustomerModel;
use App\V3\V3_2_7\Models\TallyClassModel;
use App\V3\V3_2_7\Models\TallyModel;
use App\V3\V3_2_7\Services\BarterService;
use App\V3\V3_2_7\Services\MaterielService;
use App\V3\V3_2_7\Services\SellService;
use App\V3\V3_2_7\Services\StatisticsService;
use App\Helper\Utils\TimeUtil;
use App\V3\V3_2_7\Models\MaterielContentModel;
use App\V3\V3_2_7\Models\SellGoodsDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_7\Models\ExpressModel;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_7\Models\BarterGoodsDetailModel;

class StatisticsController extends BaseController
{
    /**
     * 已销售统计
     * change 在 2021/11/11 16:35 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sell(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' => 'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id', '=', $this->getMainUserId()];
        $condition[] = ['out_status', '=', 1];
        $condition[] = ['pay_status', '=', 1];
        $condition[] = ['repeal_status', '=', 0];

        if ($data['type'] == 1) {
            $date = TimeUtil::convertDateSignToUnix();
        } elseif ($data['type'] == 2) {
            $date = TimeUtil::convertDateSignToUnix('month');
        } elseif ($data['type'] == 3) {
            $date = $this->quarter();
        }
        $tallyModel = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date', $date)
            ->groupBy('name', 'type_name')->get();
//        $modelData['data'] = $tallyModel;
//        $modelData['total_piece'] = SellGoodsDetail::where($condition)
//            ->whereBetween('created_at',$date)
//            ->sum('piece');
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value) {
            $totalMoney += $value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,type_name,materiel_no,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date', $date)
            ->groupBy('name', 'type_name')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     * 当前季度
     * change 在 2021/11/12 10:55 创建
     * @return array
     */
    public function quarter()
    {
        $moth = (int)date('m');
        if (in_array($moth, [1, 2, 3])) {
            $startDate = strtotime(date('Y') . '-01');
            $endDate = strtotime(date('Y') . '-03-31 23:59:59');
        } elseif (in_array($moth, [4, 5, 6])) {
            $startDate = strtotime(date('Y') . '-04');
            $endDate = strtotime(date('Y') . '-06-30 23:59:59');
        } elseif (in_array($moth, [7, 8, 9])) {
            $startDate = strtotime(date('Y') . '-07');
            $endDate = strtotime(date('Y') . '-09-30 23:59:59');
        } elseif (in_array($moth, [10, 11, 12])) {
            $startDate = strtotime(date('Y') . '-10');
            $endDate = strtotime(date('Y') . '-12-31 23:59:59');
        }
        return [$startDate, $endDate];
    }

    /**
     * 收入
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/6 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function incomeOrExpend(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//收支类型：0-收入 1-支出
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'type.required' => '`报表类型`缺失',
            'type.in' => '`报表类型`错误',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }
        $condition = [];
        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
            $condition[] = ['add_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '<=', $endTime];
        }
        $tallyIdArr = [];
        $tallyIdArr01 = [];
        $tallyIdArr02 = [];
        $condition['type'] = ['EQ' => $data['type']];

        if (!empty($data['storage_id'])) {
            if (!empty($data['type'])) {
                $materielContentList = MaterielContentModel::select('materiel_id')
                    ->where([
                        'repeal_status' => 0,
                        'storage_id' => $data['storage_id'],
                        'main_id' => $this->getMainUserId()
                    ])->distinct()->get()->toArray();

                if (!empty($materielContentList)) {
                    $materIdArr = array_column($materielContentList, 'materiel_id');
                    $materList = TallyModel::select(
                        'a.id'
                    )->from('tally as a')
                        ->leftJoin('materiel as b', 'a.order_no', '=', 'b.purchase_no')
                        ->where($condition)
                        ->whereIn('b.id', $materIdArr)
                        ->where([
                            'b.delete_flag' => 0,
                            'a.delete_flag' => 0,
                            'b.repeal_status' => 0,
                            ['b.purchase_no', '!=', ''],
                            ['a.order_no', '!=', ''],
                            ['b.pay_status', '!=', 0]
                        ])->get()->toArray();
                    $tallyIdArr01 = array_column($materList, 'id');
                }
                $barGoodsList = BarterGoodsDetailModel::select('barter_id')
                    ->where([
                        'delete_flag' => 0,
                        'repeal_status' => 0,
                        'storage_id' => $data['storage_id'],
                        'main_id' => $this->getMainUserId()
                    ])->distinct()->get()->toArray();
                if (!empty($barGoodsList)) {
                    $barIdArr = array_column($barGoodsList, 'barter_id');
                    $barList = TallyModel::select(
                        'a.id',
                        'b.id as barter_id',
                        'tally_class_name',
                        'b.order_no'
                    )->from('tally as a')
                        ->leftJoin('barter as b', 'a.order_no', '=', 'b.order_no')
                        ->where($condition)
                        ->whereIn('b.id', $barIdArr)
                        ->where([
                            'b.delete_flag' => 0,
                            'a.delete_flag' => 0,
                            'b.repeal_status' => 0,
                            ['b.order_no', '!=', ''],
                            ['a.order_no', '!=', ''],
                            ['b.pay_status', '!=', 0]
                        ])->get()->toArray();
                    $tallyIdArr02 = array_column($barList, 'id');
                }
            } else {
                $sellGoodsList = SellGoodsDetail::select('sell_id')
                    ->where([
                        'repeal_status' => 0,
                        'warehouse_id' => $data['storage_id'],
                        'main_id' => $this->getMainUserId()
                    ])->distinct()->get()->toArray();
                if (!empty($sellGoodsList)) {
                    $sellIdArr = array_column($sellGoodsList, 'sell_id');
                    $sellList = TallyModel::select(
                        'a.id'
                    )->from('tally as a')
                        ->leftJoin('sell as b', 'a.order_no', '=', 'b.order_no')
                        ->where($condition)
                        ->whereIn('b.id', $sellIdArr)
                        ->where([
                            'b.delete_flag' => 0,
                            'a.delete_flag' => 0,
                            'b.repeal_status' => 0,
                            ['b.order_no', '!=', ''],
                            ['a.order_no', '!=', ''],
                            ['b.pay_status', '!=', 0]
                        ])->get()->toArray();
                    $tallyIdArr01 = array_column($sellList, 'id');
                }
                $barGoodsList = BarterGoodsDetailModel::select('barter_id')
                    ->where([
                        'delete_flag' => 0,
                        'repeal_status' => 0,
                        'storage_id' => $data['storage_id'],
                        'main_id' => $this->getMainUserId()
                    ])->distinct()->get()->toArray();
                if (!empty($barGoodsList)) {
                    $barIdArr = array_column($barGoodsList, 'barter_id');
                    $barList = TallyModel::select(
                        'a.id'
                    )->from('tally as a')
                        ->leftJoin('barter as b', 'a.order_no', '=', 'b.order_no')
                        ->where($condition)
                        ->whereIn('b.id', $barIdArr)
                        ->where([
                            'b.delete_flag' => 0,
                            'a.delete_flag' => 0,
                            'b.repeal_status' => 0,
                            ['b.order_no', '!=', ''],
                            ['a.order_no', '!=', ''],
                            ['b.pay_status', '!=', 0]
                        ])->get()->toArray();
                    $tallyIdArr02 = array_column($barList, 'id');
                }
            }
            $tallyIdArr = array_unique(array_merge($tallyIdArr01, $tallyIdArr02));
        }
        $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        $condition['delete_flag'] = ['EQ' => 0];
        $totalInfo = TallyModel::selectRaw(
            'SUM(money) as money'
        )->where($condition);

        $incomeList = TallyModel::selectRaw(
            'add_time,money,tally_class_name'
        )->where($condition);

        $tallyClassId = [];
        if (isset($data['tally_class_id'])) {
            $tallyClassInfo = TallyClassModel::where('id', $data['tally_class_id'])->first();

            if ($tallyClassInfo['parent_id'] == 0) {
                //获取二级几张类型信息
                $getTallyClass = TallyClassModel::where('parent_id', $data['tally_class_id'])->get()->toArray();

                if (!empty($getTallyClass)) {
                    foreach ($getTallyClass as $value) {
                        $tallyClassId[] = $value['id'];
                    }
                }
            } else {
                $tallyClassId[] = $data['tally_class_id'];
            }

            $totalInfo->whereIn('tally_class_id', $tallyClassId);

            $incomeList->whereIn('tally_class_id', $tallyClassId);
        }
        if (!empty($tallyIdArr)) {
            $incomeList->whereIn('id', $tallyIdArr);
        }

        $totalInfo = $totalInfo->groupBy('main_id')->first();

        $result['total_money'] = empty($totalInfo) ? 0 : $totalInfo->money;

        $result['income_list'] = $incomeList->orderBy('money', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage']);

        return $this->success($result);
    }

    /**
     * 收入
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/6 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function incomeOrExpend1(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//收支类型：0-收入 1-支出
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'type.required' => '`报表类型`缺失',
            'type.in' => '`报表类型`错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
            $condition[] = ['add_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '<=', $endTime];
        }

        $condition['type'] = ['EQ' => $data['type']];

        $condition['main_id'] = ['EQ' => $this->getMainUserId()];

        $tallyClassId = [];
        if (isset($data['tally_class_id'])) {
            $tallyClassInfo = TallyClassModel::where('id', $data['tally_class_id'])->first();
            if ($tallyClassInfo['parent_id'] == 0) {
                //获取二级几张类型信息
                $getTallyClass = TallyClassModel::where('parent_id', $data['tally_class_id'])->get()->toArray();

                if (!empty($getTallyClass)) {
                    foreach ($getTallyClass as $value) {
                        $tallyClassId[] = $value['id'];
                    }
                }
            } else {
                $tallyClassId[] = $data['tally_class_id'];
            }
        }

        $totalInfo = TallyModel::selectRaw(
            'SUM(money) as money'
        )->where($condition);
        if (!empty($tallyClassId)) {
            $totalInfo->whereIn('tally_class_id', $tallyClassId);
        }
        $totalInfo = $totalInfo->groupBy('main_id')->first();

        $result['total_money'] = empty($totalInfo) ? 0 : $totalInfo->money;
        $incomeList = TallyModel::selectRaw(
            'add_time,money,tally_class_name'
        )->where($condition);
        if (!empty($tallyClassId)) {
            $incomeList->whereIn('tally_class_id', $tallyClassId);
        }
        $result['income_list'] = $incomeList->orderBy('money', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage']);

        return $this->success($result);
    }

    /**
     * 采购报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMateriel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
            $condition[] = ['a.purchase_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }

        $userInfo = [];
        if ($this->getMainUserId() == $this->getUserId()) {
            $userInfo['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $userInfo['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMateriel($condition, $data, $userInfo)
        );
    }

    /**
     * 采购报表详情
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMaterielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_id' => 'required|integer',//商品id
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'type_id.required' => '`商品id`缺失',
            'type_id.integer' => '`商品id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
            $condition[] = ['a.purchase_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMaterielDetail($data, $condition)
        );
    }

    /**
     * 成本报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/8 14:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCost(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' => [
                'required',
                Rule::In([0, 1]),//成本报表类型:0:商品;1:套餐;
            ],
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'type.required' => '请选择报表类型',
            'type.in' => '报表类型错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        }
        return $this->success(
            StatisticsService::statementCost($condition, $data)
        );
    }

    /**
     * 销售报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 13:43
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementSell(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
            $condition[] = ['sell_date', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '<=', $endTime];
        }

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(StatisticsService::statementSell($condition, $data));
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorage(Request $request)
    {

        //调用查询接口
        $condition = [];
        $storageIdArr = [];
        if ($this->getUserId() == $this->getMainUserId()) {
            //调用查询接口
            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            if ($this->isShareStorage()) {
                //调用查询接口
                $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
            } else {
                $userInfo = [
                    'user_id' => $this->getUserId(),
                    'main_id' => $this->getMainUserId()
                ];
                $storageIdArr = CommonService::getMultiUser($userInfo);
            }
        }

        return $this->success(
            StatisticsService::statementStorage($condition, $storageIdArr)
        );
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorageDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(StatisticsService::statementStorageDetail($request->storage_id, $data));
    }

    /**
     * 客户报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:02
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function statementCustomer(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementCustomer($data, $condition)
        );
    }

    /**
     * 客户报表详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCustomerDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'customer_id' => 'required|integer',//供应商或客户id
            'customer_name' => 'required',//供应商或客户id
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//统计类型;0:采购;1:销售;
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
            'customer_name.required' => '`供应商或客户名称`缺失',
            'type.required' => '`统计类型`缺失',
            'type.In' => '`统计类型`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['is_share_sell'] = $this->isShareSell();
        $data['is_share_purchase'] = $this->isSharePurchase();
        return $this->success(
            StatisticsService::statementCustomerDetail($data, $condition)
        );
    }

    /**
     * 采购商品统计
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/8/25 16:50
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsPurchasedGoods(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'customer_id' => 'required|integer',//供应商或客户id
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
            $condition[] = ['b.purchase_time', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '<=', $endTime];
        }

        if ($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }
        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $list = StatisticsService::statisticsPurchasedGoods($condition, $data, $keyword);
        $this->log('采购商品统计', $list);
        return $this->success($list);
    }

    /**
     * 客户销售商品统计
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/8/26 10:32
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsGoodsSold(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'customer_id' => 'required|integer',//供应商或客户id
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }

        $condition = [];
        if ($this->getMainUserId() == $this->getUserId()) {

            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        } else {
            $condition['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
            $condition[] = ['sell_date', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '<=', $endTime];
        }

        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $list = StatisticsService::sellGoodsList($condition, $data, $keyword);
        $this->log('客户销售商品统计', $list);
        return $this->success($list);
    }

    /**
     * 进货
     * change 在 2021/11/11 16:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stock(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' => 'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id', '=', $this->getMainUserId()];

        if ($data['type'] == 1) {
            $date = TimeUtil::convertDateSignToUnix();
        } elseif ($data['type'] == 2) {
            $date = TimeUtil::convertDateSignToUnix('month');
        } elseif ($data['type'] == 3) {
            $date = $this->quarter();
        }
        $tallyModel = MaterielContentModel::select(DB::raw("sum(num) as num,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'a.materiel_id', '=', 'b.id')
            ->where('a.main_id', $this->getMainUserId())
            ->where('in_storage_status', 2)
            ->whereBetween('a.purchase_time', $date)
            ->groupBy('materiel_name', 'type_name')->get();
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value) {
            $totalMoney += $value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = MaterielContentModel::select(DB::raw("sum(num) as num,materiel_img,materiel_name,type_name,materiel_no,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'a.materiel_id', '=', 'b.id')
            ->where('a.main_id', $this->getMainUserId())
            ->where('in_storage_status', 2)
            ->whereBetween('a.purchase_time', $date)
            ->groupBy('materiel_name', 'type_name')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     *数据预览
     * Author: zlf
     * Created at 2023/2/28 10:27
     * @param Request $request
     * @return void
     */
    public function dataPreview(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' => 'required|integer',//时间 1-今日 2-本月 3-本季

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $cond = [];
        $storageIdArr = [];
        $condition = [];
        if (!$this->isShareAllInfo() && $this->getMainUserId() != $this->getUserId()) {
            $condition['user_id'] = $this->getUserId();
            $userInfo = [
                'user_id' => $this->getUserId(),
                'main_id' => $this->getMainUserId(),
            ];
            $storageIdArr = CommonService::getMultiUser($userInfo);
            $cond['a.user_id'] = $this->getUserId();
        } else {
            $condition['main_id'] = $this->getMainUserId();
            $cond['a.main_id'] = $this->getUserId();
        }

        if ($data['type'] == 1) {
            $date = TimeUtil::convertDateSignToUnix();
        } elseif ($data['type'] == 2) {
            $date = TimeUtil::convertDateSignToUnix('month');
        } elseif ($data['type'] == 3) {
            $date[0] = strtotime(date('Y') . '-01-01 00:00:00');
            $date[1] = time();
        }
        $todayData = [];
        $res = LogOutstorageModel::getTodaySellMoney($condition, $date[0], $date[1]);//今日销售金额和总利润
        $storageManageInfo = StorageManageModel::query()->select(
            DB::raw('SUM(in_storage_num) as total_amount'),
            DB::raw('SUM(in_storage_num * materiel_mean_cost) as total_cost')
        )->from('storage_manage as a')
            ->leftJoin('storage as b', 'b.id', '=', 'a.storage_id')
            ->where([
                'a.delete_flag' => 0,
                'b.delete_flag' => 0,
            ])->where(function ($query) use ($storageIdArr) {
                if (!empty($storageIdArr)) {
                    $query->whereIn('storage_id', $storageIdArr);
                } else {
                    $query->where('a.main_id', $this->getMainUserId());
                }
            })->first();

        $todayData['total_amount'] = $storageManageInfo['total_amount'];
        $todayData['total_cost'] = $storageManageInfo['total_cost'];
        $todayData['in_storage_count'] = LogInstorageModel::getTodayInCount($condition, $date[0], $date[1]);//今日入库总数
        $todayData['out_storage_count'] = LogOutStorageModel::getTodayOutCount($condition, $date[0], $date[1]);//今日出库
        $todayData['package_count'] = LogPackageModel::getTodayPackageCount($condition, $date[0], $date[1]);//今日套餐出库总数
        $todayData['trans_storage_count'] = LogOutstorageModel::getTodayAllocateCount($condition, $date[0], $date[1]);//今日调拨数量
        $todayData['storage_warning_count'] = StorageManageModel::getTodayStorageWanringCount(['a.main_id' => $this->getMainUserId()], $date[0], $date[1], $storageIdArr);//今日预警数量
        $todayData['storage_time_warning_count'] = StorageManageModel::getTodayStorageTimeWarningCount(['a.main_id' => $this->getMainUserId()], $date[0], $date[1], $storageIdArr);//时间预警数量
        $todayData['sell_money'] = empty($res['total_sell_price']) ? 0 : $res['total_sell_price'];//今日销售金额
        $todayData['tally_income'] = TallyModel::getTodayTallyImcomeDelSellData($condition, 0, $date[0], $date[1])['today_money'] ?? 0;//今日账单收入

        $todayData['total_income_money'] = $todayData['sell_money'] + $todayData['tally_income'];//今日总收入
        $todayData['materiel_money'] = MaterielContentModel::getTodayMaterielMoney($condition, $date[0], $date[1]);//今日采购金额
        $todayData['tally_expend'] = TallyModel::getTodayTallyImcomeDelPurchaseData($condition, 1, $date[0], $date[1])['today_money'] ?? 0;//今日账单支出
        $todayData['total_expend_money'] = $todayData['materiel_money'] + $todayData['tally_expend'];//今日总支出
        $todayData['total_income'] = empty($res['total_income']) ? 0 : $res['total_income'];//今日总利润
        $todayData['total_debt'] = SellModel::getTodaySellMoney($condition, $date[0], $date[1]);//今日总欠款
        $todayData['gross_receipts'] = $todayData['total_expend_money'] - $todayData['tally_income'] + $todayData['total_debt'];//今日总收款
        $todayData['add_customer'] = SupplierCustomerModel::getTodayAddCustomer($condition, $date[0], $date[1]);//今日新增客户
        $todayData['sell_count'] = SellModel::getTodaySellCount($condition, $date[0], $date[1]);//今日销售单量
        $todayData['materiel_count'] = MaterielModel::getTodayMaterielCount($condition, $date[0], $date[1]);//今日采购数量
        $todayData['return_count'] = SalesReturnModel::getTodayReturnCount($condition, $date[0], $date[1]);//今日退货数量
        $todayData['breakage_count'] = OverflowBreakageModel::getTodaybreakageCount($condition, 1, $date[0], $date[1]);//今日报损数量
        $todayData['overflow_count'] = OverflowBreakageModel::getTodaybreakageCount($condition, 0, $date[0], $date[1]);//今日报溢数量
        $todayData['tally_count'] = TallyModel::getTodayTallyCount($condition, $date[0], $date[1]);//今日记账数量
        $todayData['product_order_count'] = ProductOrderModel::getTodayProductOrderCount($condition, 0, $date[0], $date[1]);//今日生产任务数量
        $todayData['finish_product_order_count'] = ProductOrderModel::getTodayProductOrderCount($condition, 2, $date[0], $date[1]);//今日生产(已完成)
        $todayData['unfinished_product_order_count'] = ProductOrderModel::getTodayProductOrderCount($condition, 1, $date[0], $date[1]);//今日生产(未完成)
        $todayData['express_query_count'] = ExpressModel::getQqueryExpressCount(['main_id' => $this->getMainUserId()], $date[0], $date[1]);//快递查询
        $todayData['in_total_cost'] = 0;//浏览画册
        $todayData['in_total_sell_price'] = LogInStorageModel::getInStorageMoney($cond, $date[0], $date[1])['in_total_sell_price'] ?? 0;//快速入库销售总价
        $todayData['in_total_cost'] = LogInStorageModel::getInStorageMoney($cond, $date[0], $date[1])['in_total_cost'] ?? 0;//快速入库销售总成本
        $todayData['out_total_sell_price'] = LogOutStorageModel::getOutStorageMoney($condition, $date[0], $date[1])['out_total_sell_price'] ?? 0;//快速出库销售总价
        $todayData['out_total_cost'] = LogOutStorageModel::getOutStorageMoney($condition, $date[0], $date[1])['out_total_cost'] ?? 0;//快速出库销售总成本

        $todayData['zj_in_storage_count'] = LogInstorageModel::getInCount($condition, $date[0], $date[1], 2, 1)['total_num'] ?? 0;//快速入库数量
        $todayData['zj_in_total_cost'] = LogInstorageModel::getInCount($condition, $date[0], $date[1], 2, 1)['total_cost'] ?? 0;//快速入库总成本
        $todayData['zj_in_count'] = LogInstorageModel::getCount($condition, $date) ?? 0;;//入库次数
        $todayData['zj_out_storage_count'] = LogOutStorageModel::getOutCount($condition, $date[0], $date[1], 2, 1)['total_num'] ?? 0;//快速出库数量
        $todayData['zj_out_total_price'] = LogOutStorageModel::getOutCount($condition, $date[0], $date[1], 2, 1)['total_price'] ?? 0;//快速出库价格
        $todayData['zj_out_total_cost'] = LogOutStorageModel::getOutCount($condition, $date[0], $date[1], 2, 1)['total_cost'] ?? 0;//快速出库价格
        $todayData['zj_out_count'] = LogOutStorageModel::getCount($condition, $date) ?? 0;//出库次数
        $todayData['allot_out_total_num'] = LogOutStorageModel::getOutCount($condition, $date[0], $date[1], 1, 1)['total_num'] ?? 0;//调拨出库数量
        $sell = SellService::getSellInfo($condition, $date);//销售
        $todayData = array_merge($todayData, $sell);
        $materiel = MaterielService::getMaterielInfo($condition, $date);//采购
        $todayData = array_merge($todayData, $materiel);
        $todayData['barter_total_price'] = LogOutStorageModel::getOutStorageMoney($condition, $date[0], $date[1], 9)['out_total_sell_price'] ?? 0;//换货单总价
        $todayData['barter_total_num'] = LogOutStorageModel::getOutStorageMoney($condition, $date[0], $date[1], 9)['out_total_num'] ?? 0;//换货单总数
        $todayData['return_total_price'] = LogInStorageModel::getInStorageMoney($cond, $date[0], $date[1], 8)['in_total_cost'] ?? 0;//退货总价
        $todayData['return_total_num'] = LogInStorageModel::getInStorageMoney($cond, $date[0], $date[1], 8)['in_total_num'] ?? 0;//退货总数量
        $todayData['barter_count'] = BarterService::getCount($condition, $date)['total_count'] ?? 0;//退换货单数
        $todayData['barter_spread_price'] = BarterService::getCount($condition, $date)['total_spread_price'] ?? 0;//退换货单数
        $todayData['barter_other_charges'] = BarterService::getCount($condition, $date)['barter_other_charges'] ?? 0;//换货其他价格
        $todayData['breakage_total_goods_num'] = LogOutStorageModel::getOutCount($condition, $date[0], $date[1], 1, 2)['total_num'] ?? 0;//报损商品数量
        $todayData['overflow_total_goods_num'] = LogInstorageModel::getInCount($condition, $date[0], $date[1], 1, 2)['total_num'] ?? 0;//报溢商品数量
        $todayData['tally_income_count'] = TallyModel::getTodayTallyImcomeDelSellData($condition, 0, $date[0], $date[1])['total_income_count'] ?? 0;//今日账单收入
        $todayData['tally_expend_count'] = TallyModel::getTodayTallyImcomeDelPurchaseData($condition, 1, $date[0], $date[1])['total_expend_count'] ?? 0;//今日账单支出
        $todayData['total_customer_count'] = SupplierCustomerModel::getCount($condition, $date, 1)['total_num'] ?? 0;//客户总数
        $todayData['total_supplier_count'] = SupplierCustomerModel::getCount($condition, $date, 0)['total_num'] ?? 0;//供应商总数
        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $todayData]);
    }

    /**
     *已售商品统计-客户购买详情列表
     * Author: zlf
     * Created at 2023/12/29 9:36
     * @param $request
     * @return array
     */
    public function sellGoodsBuyCustomerList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'sell_goods_id' => 'required|integer',//销售商品id
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：' . date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：' . date('Y-m-d'),
            'sell_goods_id.required' => '`销售商品id`缺失',
            'sell_goods_id.integer' => '`销售商品id`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0] . ' 00:00:00');
        }

        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0] . ' 23:59:59');
        }
        $condition = [];
        if (!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.created_at', '>=', $startTime];
            $condition[] = ['a.created_at', '<=', $endTime];
        } else if (!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.created_at', '>=', $startTime];
        } else if (empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.created_at', '<=', $endTime];
        }
        $data['main_id'] = $this->getMainUserId();
        return success(StatisticsService::sellGoodsBuyCustomerList($condition, $data));
    }
}
